import * as Koa from 'koa';
import * as Json from 'koa-json';
import * as KoaBody from 'koa-body';
import * as Cors from 'koa2-cors';
//import * as OnError from 'koa-onerror';
import { router } from './routers/demo';
import LogUtil from './app/modules/log4';
const app = new Koa();
//OnError(app)
app.use(Json());
app.use(KoaBody({
    multipart: true,
    formidable: {
      maxFileSize: 2000 * 1024 * 1024    // 设置上传文件大小最大限制，默认2M
    }
  }))
  app.use(Cors({
    origin: function (ctx:any) {
      return '*';
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE', 'PUT', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
  }))
app.use(async (ctx:any,next:any)=>{
    //console.time('ts-koa2');
    let startDate:any=new Date();
    let ms:number;
    try{
        await next();
        let endDate:any=new Date();
        ms=endDate-startDate;
        console.log(`---------START_TIME=>${startDate}------------`)
        console.log(`${ctx.method} ${ctx.host}${ctx.url} - ${ms}ms`);
        console.log(`---------END_TIME=>${endDate}-----------`)
        //console.timeEnd('ts-koa2');
        LogUtil.logResponse(ctx, ms);//记录响应日志
    }catch(error){
        let endDate:any=new Date();
        ms=endDate-startDate;
        LogUtil.logError(ctx, error, ms);//记录错误日志
        console.log('request exception');
    }
});
// routes
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000,()=>{
    console.log('server is runing !!');
});
